import express from "express";
const app = express();
//白名单
const whitelist = ["localhost", "127.0.0.1"];
//防盗链
const preventHotLinking = (req, res, next) => {
  //referer 如何取 referer如果是直接打开的资源是获取不到的,必须要发起请求后才能获取到
  const referer = req.get("referer");
  console.log("referer: ", referer, new URL(referer));
  if (referer) {
    const { hostname } = new URL(referer);
    if (hostname && !whitelist.includes(hostname)) {
      res.status(403).send("Forbidden 禁止访问");
    }
  }
  next();
};
app.use(preventHotLinking);
//第一个参数是自定义前缀 放入一个资源目录 访问时直接访问这个目录，不需要加static http://localhost:3000/bg.jpg
app.use("/assets", express.static("static"));
app.listen(3001, () => {
  console.log("Server is running on port 3000");
});
